/**
 * 
 */
package com.manage.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.auth.model.Account;
import com.manage.model.Channel;
import com.manage.config.Config;
import com.service.AbstractService;
import com.util.ConfigUtil;
import com.utils.dbcp.ConnectionManager;
import com.utils.dbcp.ModelGenerator;

public class ChannelServiceImpl extends AbstractService implements ChannelService
{
	private Logger logger;
	
	public ChannelServiceImpl()
	{
		logger = Logger.getLogger(this.getClass());
		this.dbcp = ConfigUtil.get(Config.BOSSSECTION, Config.KEY_DBCP_NAME);
	}
		
	@Override
	public Channel getChannel(int id) 
	{
		String sql = "select * from t_channel where id=" + String.valueOf(id) + "";
		ModelGenerator<Channel> dbcpmg = new ModelGenerator<Channel>(Channel.class);
		return dbcpmg.generate(dbcp, sql);
	}

	@Override
	public List<Channel> getChannels()
	{
		String sql = "select * from t_channel order by id";
		logger.debug("sql: " + sql);
		ModelGenerator<Channel> dbcpmg = new ModelGenerator<Channel>(Channel.class);
		return dbcpmg.generateList(dbcp, sql);
	}
	
	@Override
	public boolean saveChannel(Account operator, String type, Channel channel)
	{
		if (operator == null || operator.getId() == null || operator.getId().length() == 0)
			return false;
		
		String sql = "";
		if (type.equalsIgnoreCase("insert"))
		{
			channel.setId(getTableId("channel"));
			sql = 
				"insert into channel(id,name,company,bd,contractdate,contractend) " +
				"values(" + String.valueOf(channel.getId()) + ",'" + encodeDb(channel.getName()) + "','" + encodeDb(channel.getCompany()) + "','" +
						encodeDb(channel.getBd()) + "','" + channel.getContractDate() + "','" + 
						channel.getContractEnd() + "')";
			
		}
		else if (type.equalsIgnoreCase("update"))
		{
			sql = 
				"update channel set name='" + encodeDb(channel.getName()) + "'," +
						"company='" + encodeDb(channel.getCompany()) + "'," +
						"bd='" + encodeDb(channel.getBd()) + "'," +
						"contractdate='" + channel.getContractDate() + "'," + 
						"contractend='" + channel.getContractEnd() + "' " +
				" where id=" + String.valueOf(channel.getId()) + "";
		}
		else if (type.equalsIgnoreCase("delete"))
		{
			sql = "delete from channel where id=" + String.valueOf(channel.getId()) + "";
		}
		else
		{
			sql = "";
		}
		logger.debug("sql: " + sql);
		if (sql.length() > 0)
		{
			if (ConnectionManager.getInstance().execute(dbcp, sql))
			{
				Channel lo = null;
				if (!type.equals("delete"))
				{
					lo = getChannel(channel.getId());
				}
				logTableOperate("channel", type, operator, lo);
				return true;
			}
		}		
		return false;
	}
}
